#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash cp2k-7.1.0.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
yum install -y  environment-modules time patch libatomic autoconf automake libtool numactl binutils systemd-devel valgrind flex wget gmp mpfr
set -e
cp Linux-x86-64-gfortran.psmp.patch $buildpath
wget -t 40 -c -P $buildpath https://github.com/cp2k/cp2k/archive/refs/tags/v7.1.0.tar.gz
tar xf $buildpath/v7.1.0.tar.gz -C $buildpath && rm -rf $buildpath/v7.1.0.tar.gz
cd $buildpath/cp2k-7.1.0/arch  
cp $buildpath/Linux-x86-64-gfortran.psmp.patch ./
patch -p0 Linux-x86-64-gfortran.psmp Linux-x86-64-gfortran.psmp.patch
cd $buildpath/cp2k-7.1.0/exts/dbcsr
wget -t 40 -c https://github.com/cp2k/dbcsr/releases/download/v2.0.1/dbcsr-2.0.1.tar.gz
tar -xvf dbcsr-2.0.1.tar.gz
mv dbcsr-2.0.1/* ./ 
cd ../..
make -j$(nproc) ARCH=Linux-x86-64-gfortran VERSION=psmp
mkdir -p $installpath/cp2k-7.1.0 && cp -r $buildpath/cp2k-7.1.0/* $installpath/cp2k-7.1.0
cat>"$installpath/cp2k-7.1.0/cp2k_modulefiles"<<EOF
#%Module1.0
conflict cp2k
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set CP2K \$pwd
setenv CP2K \$CP2K
prepend-path PATH \$CP2K/exe/Linux-x86-64-gfortran
prepend-path LD_LIBRARY_PATH \$CP2K/lib
prepend-path CP2K_DATA_DIR \$CP2K/data
EOF

rm -rf $buildpath/cp2k-7.1.0
